package com.controller;

import com.beans.ErrorStatusEnum;
import com.beans.InformationEntity;
import com.common.entity.R;
import com.common.utils.UploadFileUtil;
import com.repository.InformationRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 行业资讯、公司动态 CRUD
 *
 * @author gm
 * @date 2020/6/2
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("information")
public class InformationController {

    @PersistenceContext
    private EntityManager entityManager;
    @Resource
    private InformationRepository informationRepository;
    @Resource
    private UploadFileUtil uploadFileUtil;

    /**
     * 获取所有行业资讯
     *
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/2
     */
    @GetMapping("getInformation")
    public R getInformation() {
        List<InformationEntity> resultList = informationRepository.findAll();
        Object total = entityManager.createNativeQuery("select count(id) from information").getSingleResult();
        R ok = R.ok();
        ok.put("rows", resultList);
        ok.put("total", total);
        return ok;
    }

    /**
     * 分页获取行业资讯
     *
     * @param type  !类型（ 1.行业资讯 2.公司动态 ）
     * @param page  第几页
     * @param rows  每页几条数据
     * @param sort  排序字段名
     * @param order 排序方式  asc desc
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/2
     */
    @GetMapping("getInformationForPage")
    public R getInformationForPage(Integer type, Integer state, Integer page, Integer rows, String sort, String order) {
        //region 组装hql
        StringBuilder sql = new StringBuilder("select * from information where 1 = 1 ");
        StringBuilder countSql = new StringBuilder("select count(id) from information where 1 = 1 ");
        if(type != null){
            sql.append(" and type = :type ");
            countSql.append(" and type = :type ");
        }
        if (state != null) {
            sql.append(" and state = :state ");
            countSql.append(" and state = :state ");
        }
        if (!StringUtils.isEmpty(sort)) {
            sql.append(" order by ").append(sort).append(" ");
            if (!StringUtils.isEmpty(order)) {
                sql.append(order);
            }
        }
        if (page != null && rows != null) {
            sql.append(" limit :offset , :rows ");
        }
        //endregion 组装hql
        //region 组装查询对象和参数
        Query query = entityManager.createNativeQuery(sql.toString(), InformationEntity.class);
        Query queryCount = entityManager.createNativeQuery(countSql.toString());
        if(type != null){
            query.setParameter("type", type);
            queryCount.setParameter("type", type);
        }
        if (state != null) {
            query.setParameter("state", state);
            queryCount.setParameter("state", state);
        }
        if (page != null && rows != null) {
            query.setParameter("offset", (page - 1) * rows).setParameter("rows", rows);
        }
        List<InformationEntity> resultList = query.getResultList();
        Object count = queryCount.getSingleResult();
        R ok = R.ok();
        ok.put("total", count);
        ok.put("rows", resultList);
        return ok;
    }

    /**
     * 新增/修改行业资讯
     *
     * @param information
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/2
     */
    @PostMapping("saveOrUpdateInformation")
    public R saveOrUpdateInformation(@Valid InformationEntity information, @RequestParam(value = "informationIcon", required = false) MultipartFile informationIcon) {

        if (informationIcon != null) {
            //类型4为行业资讯缩略图
            String fileType = "4";
            R r = uploadFileUtil.uploadPicture(informationIcon, fileType);
            //如果图片保存成功，就插入数据
            if (ErrorStatusEnum.OK.code().equals(r.get(R.CODE))) {
                //文件url
                String url = (String) r.get(R.DATA);
                information.setIcon(url);
                information.setUpdateTime(new Date());
                information = entityManager.merge(information);
                return R.ok(information);
            } else {
                //图片保存失败，返回错误对象
                return r;
            }
        }
        //如果不需要上传图片，就直接保存
        information.setUpdateTime(new Date());
        information = entityManager.merge(information);
        return R.ok(information);

    }

    /**
     * 删除行业资讯
     *
     * @param ids
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/2
     */
    @PostMapping("deleteInformation")
    public R deleteInformation(@RequestParam(value = "ids[]") List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return R.error(ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.code(), "删除操作，id不能为空!");
        }
        entityManager.createNativeQuery("update information set state = 0 where id in :id").setParameter("id", ids).executeUpdate();
        return R.ok();
    }

    /**
     * 模糊查询行业资讯
     *
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/2
     */
    @GetMapping("getInformationLikeTitle")
    public R getInformationLikeTitle(Integer type, String title) {
        if (type == null) {
            return R.error(ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.code(), ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.message());
        }
        if(StringUtils.isEmpty(title)){
            return R.ok();
        }
        List<InformationEntity> resultList = entityManager.createQuery("from InformationEntity where state = 1 and type = :type and title like :title ",InformationEntity.class).setParameter("type",type).setParameter("title", "%"+title+"%").setMaxResults(100).getResultList();

        return R.ok(resultList);
    }

}
